package com.xt.service.impl;

import com.xt.bean.Course;
import com.xt.dao.CourseRepository;
import com.xt.service.CourseService;
import com.xt.utils.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * Created by XT on 2018/5/4.
 */
@Service
public class CourseServiceImpl implements CourseService {

    @Autowired
    private CourseRepository cr;

    @Override
    public void saveOrUpdateOne(Course c){

        if (StringUtils.isEmpty(c.getId())){
            //新增
            c.setCreateDate(new Date());
        }

        c.setUpdateDate(new Date());
        cr.save(c);
    }

    @Override
    public void deleteOne(String id){
        //删除关联关系

        cr.delete(id);
    }

    @Override
    public Course getById(String id){
        return cr.findOne(id);
    }

    @Override
    public Page<Course> getListByPage(String departmentId, String specialtyId, String name, int count, int pageNo, String sortDirection, String... sortField) {

        Page<Course> coursePage = null;
        if (StringUtils.isEmpty(specialtyId) && StringUtils.isEmpty(departmentId) && StringUtils.isEmpty(name)) {
            //查询条件全空：查询全部
            coursePage = cr.findAll(PageUtil.getPageable(count, pageNo, sortDirection, sortField));
        } else if (!StringUtils.isEmpty(departmentId) && !StringUtils.isEmpty(name) && StringUtils.isEmpty(specialtyId)) {
            //院系和名称不为空，专业为空
            coursePage = cr.findByDepartmentIdAndNameLike(departmentId, name, PageUtil.getPageable(count, pageNo, sortDirection, sortField));
        } else if (StringUtils.isEmpty(specialtyId) && StringUtils.isEmpty(departmentId) && !StringUtils.isEmpty(name)) {
            //院系和专业为空 名称不为空
            coursePage = cr.findByNameLike(name, PageUtil.getPageable(count, pageNo, sortDirection, sortField));
        } else if (StringUtils.isEmpty(specialtyId) && !StringUtils.isEmpty(departmentId) && StringUtils.isEmpty(name)) {
            //名称和专业为空院系不为空
            coursePage = cr.findByDepartmentId(departmentId, PageUtil.getPageable(count, pageNo, sortDirection, sortField));
        } else if (!StringUtils.isEmpty(specialtyId) && !StringUtils.isEmpty(departmentId) && !StringUtils.isEmpty(name)) {
            coursePage = cr.findByDepartmentIdAndSpecialtyIdAndNameLike(departmentId, specialtyId, name, PageUtil.getPageable(count, pageNo, sortDirection, sortField));
        } else if (!StringUtils.isEmpty(specialtyId) && !StringUtils.isEmpty(departmentId) && StringUtils.isEmpty(name)) {
            coursePage = cr.findByDepartmentIdAndSpecialtyId(departmentId, specialtyId, PageUtil.getPageable(count, pageNo, sortDirection, sortField));
        }
        return coursePage;
    }



}

